﻿using System.Configuration;
using System.IO;
using Ionic.Zip;
using UpdaterComponents.Common;

namespace UpdaterComponents.Tasks
{
    public class DecompressPackage : ITask
    {
        private string _Message;

        public DecompressPackage()
        {
            _Message = "Decompressing Package";
        }

        #region ITask Members

        public string Message
        {
            get { return _Message; }
            set { _Message = value; }
        }

        public void DoTask()
        {
           
            DeCompress();

            DeleteTheCompressedFile();

            DeleteTheUpdaterFiles();
        }

        public void RollBack()
        {
            File.AppendAllText("UpgradeLog.txt", "Failed during decompression \n");
            
            string sUpdatesFile = ConfigurationManager.AppSettings["ReleasesXmlFile"];

            //Delete the new release folder 

            if (Directory.Exists( "NewRealease"))
                Directory.Delete("NewRealease", true);

            //Delete the directories         


            if (Directory.Exists(BackUpCreator.BackUpFolderName))
                Directory.Delete(BackUpCreator.BackUpFolderName, true);


            if (File.Exists(sUpdatesFile))
                File.Delete(sUpdatesFile);


        }

        #endregion

        private bool DeleteTheUpdaterFiles()
        {
            string sFiles = ConfigurationManager.AppSettings["UpdaterFiles"];
            char[] seperator = { ',' };
            string[] FileCollection = sFiles.Split(seperator);

            foreach (string sFile in FileCollection)
            {
                File.Delete("NewRelease\\"+sFile);
            }

            return true;
        }

        private bool DeleteTheCompressedFile()
        {
            string sAppName = ConfigurationManager.AppSettings["ApplicationName"];

            File.Delete("NewRelease\\" + sAppName +".zip");

            return true;
            
        }

        private bool DeCompress()
        {
            string sAppName = ConfigurationManager.AppSettings["ApplicationName"];
            string sFileToBeExtracted = "NewRelease\\" + sAppName + ".zip";
            string sTargetDir = "NewRelease";
            using (ZipFile zip = ZipFile.Read(sFileToBeExtracted))
            {
                zip.ExtractAll(sTargetDir, ExtractExistingFileAction.OverwriteSilently);
              
            }

            return true;
        }
    }
}
